package network.serializing;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Vector;

import network.protocol.NetworkInit;

import physics.Body;
import physics.collision.Pair;
import physics.joints.Joint;
import physics.sleeping.Connection;
public class SerializeInit {
	public static byte[] toData(NetworkInit init) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out;
		try {
			out = new ObjectOutputStream(bos);
			out.writeObject(init);
			byte[] bytes = bos.toByteArray();
			out.close();
			bos.close();
			return bytes;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static NetworkInit fromData(byte[] bytes) {
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		try {
			ObjectInput in = new ObjectInputStream(bis);
			Object o = in.readObject();
			bis.close();
			in.close();
			return recreate((NetworkInit) o);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	// Initializes the transient variables in the game
	private static NetworkInit recreate(NetworkInit init) {
		Body b;
		for (int i = 0; i < init.game.engine.world.numBodies; i++) {
			b = init.game.engine.world.getBody(i);
			b.connections = new Vector<Connection>();
			b.pairs = new Vector<Pair>();
		}
		Joint j;
		for (int i = 0; i < init.game.engine.world.numJoints; i++) {
			j = init.game.engine.world.getJoint(i);
			j.setWorld(init.game.engine.world);
			j.updateBodies();
		}
		init.game.engine.world.setUp();
		for (int i = 0; i < init.game.numGameObjects; i++) {
			init.game.getGameObject(i).setGame(init.game);
		}
		init.game.controlHandling.setUp(init.id);
		return init;
	}
}
